import { getUserInfo, getUserMenus, userLogin, activeRole, getSettings } from "@/service/login";
import { getCache, setCache } from "@/utils/cache";
import { addRoleRouter, currentRole } from "@/utils/getCurrentRole";
import router from "@/router";

export const loginStore = {
  state: {
    menus: [],
    userInfo: {},
    role: {}
  },
  mutations: {
    changeMenus(state, menus) {
      state.menus = menus;
    },
    changeUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    changeRole(state, role) {
      state.role = role;
    }
  },
  actions: {
    async loginAction({ commit }, data) {
      const { id, token } = await userLogin(data);
      setCache("token", token);

      //    getUserinfo
      const userInfo = await getUserInfo(id);
      commit("changeUserInfo", userInfo);
      setCache("userInfo", userInfo);
      // settings
      const settings = await getSettings();
      setCache("settings", settings.value);

      //    getRoleMenus
      const role = currentRole(userInfo.roles);
      commit("changeRole", role);
      setCache("role", role);

      const menus = await getUserMenus(role.id);
      commit("changeMenus", menus);
      setCache("menus", menus);

      addRoleRouter(menus);

      await router.push("/");
    },
    resetStoreCache({ commit }) {
      const userInfo = getCache("userInfo");
      if (userInfo) {
        commit("changeUserInfo", userInfo);
      }

      const role = getCache("role");
      if (role) {
        commit("changeRole", role);
      }

      const menus = getCache("menus");
      if (menus) {
        commit("changeMenus", menus);
        addRoleRouter(menus);
      }
    },
    /**
     * 切换角色
     * @param commit
     * @param data
     * @returns {Promise<void>}
     */
    async changeRoleActions({ commit }, data) {
      const role = await activeRole(data);

      // 重新拿用户信息
      const userInfo = await getUserInfo(getCache("userInfo")?.id);
      commit("changeUserInfo", userInfo);
      setCache("userInfo", userInfo);

      commit("changeRole", role);
      setCache("role", role);

      const menus = await getUserMenus(role.id);

      commit("changeMenus", menus);
      setCache("menus", menus);

      addRoleRouter(menus);

      await router.push("/");
    }
  }
};
